<?php

namespace App\Http\Controllers\NewPay;

use App\Exports\TemplateExport;
use App\Http\Controllers\Controller;
use App\Models\Pay\PayImportData;
use App\Models\Pay\PayImportTemplate;
use App\Models\Pay\PayReportFields;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class PayImportTemplateController extends Controller
{
    /**
     * 导入模板列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function payImportTemplateList(Request $request)
    {
        $params = $request->all();
        $data = $this->getPayImportTemplateList($params)->get()->toArray();
        if ($data) {
            $data = $this->transData($data);
        }

        return response()->formatJson($data);
    }

    public function getPayImportTemplateList($params)
    {
        $query = PayImportTemplate::query();

        if (isset($params['table_name'])) {
            $query->where('table_name', 'like', '%'.$params['table_name'].'%');
        }

        return $query->orderByDesc('updated_at');
    }

    public function transData($data)
    {
        $result = [];
        $columnType = [
            'string'     => '文本',
            'amount'     => '金额',
            'date'       => '日期',
            'integer'    => '整数',
            'number'     => '数字',
            'percentage' => '百分比',
        ];
        $data = collect($data)->groupBy('table_name')->toArray();

        foreach ($data as $key => $item) {
            $date = collect($item)->sortByDesc('updated_at')->first();
            $item = collect($item)->sortBy('sort')->toArray();
            $item = $this->rebuildKeys($item);
            foreach ($item as $k => $v) {
                $item[$k]['column_type_name'] = isset($v['column_type']) ? $columnType[$v['column_type']] : '';
            }
            $result[] = [
                'table_name'        => $key,
                'table_name_before' => $key,
                'columns'           => [
                    [
                        'title' => '列名',
                        'key'   => 'column_name',
                    ],
                    [
                        'title' => '数据类型',
                        'key'   => 'column_type_name',
                    ],
                    [
                        'title' => '排序值',
                        'key'   => 'sort',
                    ],
                ],
                'data'              => $item,
                'updated_at'        => $date['updated_at'],
            ];
        }

        return $result;
    }

    /**
     * 创建
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function store(Request $request)
    {
        $tableName = $request->input('table_name');
        $insertData = $request->input('insert');

        $insertData = $this->buildInsertData($tableName, $insertData);

        $result = PayImportTemplate::query()->insert($insertData);
        $message = $result ? '添加成功' : '添加失败';

        return response()->formatJson($result, $message);
    }

    public function buildInsertData($tableName, $insertData)
    {
        $date = Carbon::now();
        foreach ($insertData as $k => $v) {
            unset($insertData[$k]['_XID']);
            $insertData[$k]['table_name'] = $tableName;
            $insertData[$k]['created_at'] = $insertData[$k]['updated_at'] = $date;
        }

        return $insertData;
    }

    /**
     * 修改模板
     *
     * @param  Request  $request
     * @param           $tableName
     *
     * @return mixed
     */
    public function update(Request $request, $tableName)
    {
        $params = $request->all();

        $tableNameBefore = $params['tableNameBefore'];

        if ($params['insert']) {
            $insertData = $this->buildInsertData($tableNameBefore, $params['insert']);
            PayImportTemplate::query()->insert($insertData);
        }

        if ($params['update']) {
            foreach ($params['update'] as $k => $v) {
                $payImportTemplate = PayImportTemplate::query()->find($v['id']);
                $payImportTemplate->update($v);
            }
        }

        if ($params['delete']) {
            $ids = array_column($params['delete'], 'id');
            PayImportTemplate::destroy($ids);
        }

        if ($tableName !== $tableNameBefore) {
            PayImportTemplate::query()->where('table_name', $tableNameBefore)->update(['table_name' => $tableName]);
            PayImportData::query()->where('table_name', $tableNameBefore)->update(['table_name' => $tableName]);
            PayReportFields::query()->where('table_name', $tableNameBefore)->update(['table_name' => $tableName]);
        }

        return response()->formatJson(true, '修改成功');
    }

    /**
     * 删除车辆信息
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function destroy(Request $request)
    {
        $result = false;
        if ($request->has('table_name')) {
            $delCount = PayImportTemplate::query()->where('table_name', $request->input('table_name'))->delete();
            $result = $delCount !== 0;
        }

        $message = $result ? '删除成功' : '删除失败';

        return response()->formatJson($result, $message);
    }

    /**
     * 导出充电登记
     *
     * @param  Request  $request
     *
     * @return BinaryFileResponse
     */
    public function exportTemplate(Request $request): BinaryFileResponse
    {
        return Excel::download(new TemplateExport($request->input('tableName')), $request->input('tableName').'.xlsx');
    }

    public function rebuildKeys($array)
    {
        if (! is_array($array)) {
            return $array;
        }
        $keys = implode('', array_keys($array));
        if (is_numeric($keys)) {
            $array = array_values($array);
        }
        $array = array_map([$this, 'rebuildKeys'], $array);

        return $array;
    }
}
